/**
 * 
 */
package com.monkeyboy.security.social.qq;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.Connection;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.AbstractView;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 *
 * @author Gavin<br>
 *         2019年9月16日
 */
//注意，这里的名字必须为connect/status====>查看ConnectController源码种的第200行代码可以知道返回的视图字符串路径为/connect/status
//注意，这儿有一个代理的问题，需要配置下spring.aop.proxy-target-class=false或者移除devtools依赖
@Component("connect/status") 
public class QQConnectionStatusView extends AbstractView {
	@Autowired
	private ObjectMapper objectMapper;

	/*
	 * 由于springsocial返回connect/status这个视图的时候会尝试冲容器中寻找是否有connect/status名字的视图组件来处理（
	 * 默认是没有的，所以这儿需要我们添加一个名字为connect/status的视图组件来处理这个视图）
	 */
	@SuppressWarnings("unchecked")
	@Override
	protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String, List<Connection<?>>> connections = (Map<String, List<Connection<?>>>) model.get("connectionMap");
		// key :社交供应商id value：是否绑定
		Map<String, Boolean> bindResult = new HashMap<>();
		for (String providerId : connections.keySet()) {
			bindResult.put(providerId, CollectionUtils.isNotEmpty(connections.get(providerId)));
		}
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(objectMapper.writeValueAsString(bindResult));// 返回json
	}

}
